function MarmotQuery(id, viewModel) {
	this.id = id;
}

MarmotQuery.prototype = new DoradoComponent();

DoradoFactory.registerComponentType("MarmotQuery", function (id, viewModel) {
	return new MarmotQuery(id, viewModel);
});

MarmotQuery.prototype.destroy = function () {
	this._schemaMenuItem = null;
	this._commandQueryBox = null;
};

MarmotQuery.prototype.activate = function () {
	setTimeout(this.id + ".init()", 0);
}

MarmotQuery.prototype.init = function () {
	this.queryDataset = getDataset(this.queryDataset);
	this.conditionDataset = getDataset(this.conditionDataset);
	this.queryButton = getControl(this.queryButton);
	
	var queryDataset = this.queryDataset;
	var conditionDataset = this.conditionDataset;
	var queryButton = this.queryButton;
	if (this.queryButton) {
		var menu, menuItem;
		if (queryButton != null) {
			var menu = DoradoFactory.create("Menu");
			menu.activate();
			queryButton.setMenu(menu);
			menuItem = menu.getTopItem();
			this._schemaMenuItem = menuItem;
		}
		
		if (menu && menuItem) {
			var marmotQuery = this;
			EventManager.addDoradoEvent(menu, "onItemClick", function (menu, item) {
				if (queryDataset == null) {
					return;
				}
				
				var name = item.getName();
				switch (name) {
				  case "save":
					var command = marmotQuery._getCommandSaveQuerySchema();
					if (command != null) {
						command.clearDatasetInfos();
						command.addDatasetInfo(marmotQuery._getDatasetQueryParameter(), "all-visible");
						var parameters = command.parameters();
						parameters.clear();
						parameters.setValue("category", marmotQuery.category);
						parameters.setValue("queryId", menu._currentSchemaItem.queryId);
						parameters.setValue("overwrite", true);
						command.execute();
					}
					break;
					
				  case "save-as":
					var command = marmotQuery._getCommandSaveQuerySchema();
					if (command != null) {
						command.clearDatasetInfos();
						command.addDatasetInfo(marmotQuery._getDatasetQuery(), "current");
						command.addDatasetInfo(marmotQuery._getDatasetQueryParameter(), "all-visible");
						var parameters = command.parameters();
						parameters.clear();
						parameters.setValue("category", marmotQuery.category);
						parameters.setValue("overwrite", false);
						parameters.setValue("queryType", "STANDARD");
						var command = marmotQuery._getCommandSaveQuerySchemaAs();
						command.execute();
					}
					break;
					
				  case "maintain":
					var command = marmotQuery._getCommandQueryMaintain();
					command.execute();
					break;

				  default:
					if (item.isQuerySchema) {
						marmotQuery.clearOldParameters();
						var queryId = item.queryId;
						if (!queryId) queryId = null;
						queryDataset.parameters().setValue("__queryId", queryId);
						
						if (conditionDataset) {
							if (item.queryType && item.queryType.toLowerCase() == "standard") {
								var datasetParameter = marmotQuery._getDatasetQueryParameter();
								datasetParameter.parameters().clear();
								datasetParameter.parameters().setValue("queryId", queryId);
								datasetParameter.flushDataAsync(function (succeed) {
									if (succeed) {
										__parameter2QueryCondition(datasetParameter, conditionDataset);
									}
								});
							} else {
								conditionDataset.clearData();
							}
						}
						
						var showLoadingTip = queryDataset.isShowLoadingTip();
						queryDataset.setShowLoadingTip(true);
						queryDataset.flushDataAsync(function () {
							if (item.getName() == "empty") {
								menu._currentSchemaItem = null;
							} else {
								menu._currentSchemaItem = item;
							}
							queryDataset.setShowLoadingTip(showLoadingTip);
						});
					}
					break;
				}
			});
			
			EventManager.addDoradoEvent(menu, "onRefreshItem", function (menu, cell, item) {
				if (queryDataset == null) {
					return;
				}
				switch (item.getName()) {
				  case "save":
					var currentSchemaItem = menu._currentSchemaItem;
					var label = "\u4fdd\u5b58\u5e76\u8986\u76d6";
					if (currentSchemaItem) {
						item.setTag(currentSchemaItem.getName());
						item.setLabel(label + "\"" + currentSchemaItem.getLabel() + "\"");
						item.setDisabled(false);
					} else {
						item.setLabel(label);
						item.setDisabled(true);
					}
					break;
				  case "save-as":
					break;
				}
				return true;
			});
			this.refreshSchemaMenuItems();
		}
	}
};

MarmotQuery.prototype.refreshSchemaMenuItems = function () {
	var dataset = this._getDatasetQuery();
	var parentItem = this._schemaMenuItem;
	if (!parentItem) {
		return;
	}
	
	var marmotQuery = this;
	dataset.parameters().clear();
	dataset.parameters().setValue("category", this.category);
	dataset.flushDataAsync(function (succeed) {
		if (succeed) {
			marmotQuery._refreshSchemaMenuItems(dataset, parentItem);
		}
	});
};

MarmotQuery.prototype._refreshSchemaMenuItems = function (dataset, parentItem) {
	parentItem.getItems().clear();
	var item = new MenuItem("empty", "<\u65e0>");
	item.setIcon(__CONTEXT_PATH + "/marmot/query/images/query.gif");
	item.isQuerySchema = true;
	parentItem.addItem(item);
	parentItem.addItem(new MenuItemSeperator());
	var hasSchema = false;
	if (dataset.getCurrent()) {
		var record = dataset.getFirstRecord();
		while (record != null) {
			var label = record.getValue("queryName");
			if (record.getValue("default")) {
				label += " *";
			}
			var item = new MenuItem(record.getValue("id"), label);
			item.setIcon(__CONTEXT_PATH + "/marmot/query/images/query.gif");
			item.isQuerySchema = true;
			item.queryId = record.getValue("id");
			item.queryType = record.getValue("type");
			parentItem.addItem(item);
			hasSchema = true;
			record = record.getNextRecord();
		}
	}
	if (hasSchema) {
		parentItem.addItem(new MenuItemSeperator());
	}
	var saveParentItem;
	item = new MenuItem("save-item", "\u4fdd\u5b58\u67e5\u8be2\u65b9\u6848");
	item.setIcon(__CONTEXT_PATH + "/marmot/query/images/save.gif");
	parentItem.addItem(item);
	saveParentItem = item;
	item = new MenuItem("maintain", "\u67e5\u8be2\u65b9\u6848\u7ef4\u62a4");
	item.setIcon(__CONTEXT_PATH + "/marmot/query/images/maintain.gif");
	parentItem.addItem(item);
	item = new MenuItem("save");
	saveParentItem.addItem(item);
	item = new MenuItem("save-as", "\u53e6\u5b58\u4e3a");
	saveParentItem.addItem(item);
};

MarmotQuery.prototype.showQueryBox = function () {
	var command = this._commandQueryBox;
	if (!command) {
		command = DoradoFactory.create("RequestCommand");
		command.activate();
		this._commandQueryBox = command;
		command.setPath("/query.showDialog.d");
		command.setMethod("post");
		var parameters = command.parameters();
		parameters.clear();
		parameters.setValue("marmotQuery", this.id);
		parameters.setValue("category", this.category);
		if (this.showDynaTab) {
			parameters.setValue("showDyna", this.showDynaTab);
		}
		if (this.showSQLTab) {
			parameters.setValue("showSQL", this.showSQLTab);
		}
		if (this.conditionPage) {
			parameters.setValue("conditionPage", this.conditionPage);
		}
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setCachable(true);
		frame.setWidth((this.queryBoxwidth) ? this.queryBoxwidth : 640);
		frame.setHeight((this.queryBoxHeight) ? this.queryBoxHeight : 420);
	}
	
	var win = command.execute();
	if (this._schemaMenuItem) {
		var marmotQuery = this;
		EventManager.addDoradoEvent(win, "afterHide", function (win) {
			EventManager.removeDoradoEvent(win, "afterHide", this);
			var frame = win.getContentContainer().firstChild;
			if (frame != null && frame.contentWindow.schemaChanged) {
				marmotQuery.refreshSchemaMenuItems();
			}
		});
	}
	return win;
};

MarmotQuery.prototype._getDatasetQuery = function () {
	var dataset = getDataset("$datasetQuery");
	if (!dataset) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetQuery", "custom");
		dataset.addField("id", 1);
		dataset.addField("queryName", 1);
		dataset.addField("category", 1);
		dataset.addField("type", 1);
		dataset.addField("default", 9);
		dataset.activate();
	}
	return dataset;
};

MarmotQuery.prototype._getDatasetQueryParameter = function () {
	var dataset = getDataset("$datasetQueryParameter");
	if (!dataset) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetQueryParameter", "custom");
		dataset.addField("id", 1);
		dataset.addField("paramName", 1);
		dataset.addField("paramType", 1);
		dataset.addField("paramValue", 1);
		dataset.activate();
	}
	return dataset;
};

MarmotQuery.prototype._getCommandSaveQuerySchema = function () {
	var datasetParameter = this._getDatasetQueryParameter();
	if (__queryCondition2Parameter(this.conditionDataset, datasetParameter)) {
		var command = getControl("$commandSaveQuerySchema");
		if (!command) {
			command = DoradoFactory.create("MarmotUpdateCommand", null, "$commandSaveQuerySchema");			
			command.setAction(__MARMOT_DEFAULT_UPDATE_ACTION);
			command.setResolver("marmot.queryBoxBackBean");
			command.setMethod("replaceQueryQuickly");
			command.setAsync(true);
			var marmotQuery = this;
			EventManager.addDoradoEvent(command, "beforeExecute", function (command) {
				var parameters = command.parameters();
				var queryName = parameters.getValue("queryName");
				if (!parameters.getValue("overwrite") && queryName) {
					var dataset = marmotQuery._getDatasetQuery();
					dataset.clearData();
					dataset.insertRecord();
					dataset.setValue("queryName", queryName);
					dataset.postRecord();
				}
			});
			EventManager.addDoradoEvent(command, "onSuccess", function (command) {
				if (!command.parameters().getValue("overwrite")) {
					marmotQuery.refreshSchemaMenuItems();
				}
			});
			command.activate();
		}
		return command;
	}
	else {
		return null;
	}
}

MarmotQuery.prototype._getCommandSaveQuerySchemaAs = function () {
	var command = getControl("$commandSaveQuerySchemaAs");
	if (!command) {
		command = DoradoFactory.create("RequestCommand", null, "$commandSaveQuerySchemaAs");
		command.setPath("/query.saveDialog.d");
		command.setMethod("post");
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setCenter(true);
		frame.setWidth(300);
		frame.setHeight(180);
		var updateCommand = this._getCommandSaveQuerySchema();
		command.parameters().setValue("updateCommand", updateCommand.id);
		command.activate();
	}
	return command;
}

MarmotQuery.prototype._getCommandQueryMaintain = function () {
	var command = getControl("$commandQueryMaintain");
	if (!command) {
		command = DoradoFactory.create("RequestCommand", null, "$commandQueryMaintain");
		command.setPath("/query.maintain.d");
		command.setMethod("post");
		command.parameters().setValue("category", this.category);
		command.parameters().setValue("functionRefreshQueries", "__refreshQuerySchema");
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setCenter(true);
		frame.setWidth(450);
		frame.setHeight(280);
		command.activate();
		
		var marmotQuery = this;
		EventManager.addDoradoEvent(command, "onSuccess", function (command) {
			marmotQuery.refreshSchemaMenuItems();
		});
	}
	return command;
}

MarmotQuery.prototype.clearOldParameters = function () {
	var dataset = this.queryDataset;
	var parameters = dataset.parameters();
	var protectedParameterArray;
	if (this.protectedParameters) {
		protectedParameterArray = this.protectedParameters.split(',');
	}
	else {
		protectedParameterArray = [];
	}
	
	var size = parameters.size();
	for (var i = size - 1; i >= 0; i--) {
		var parameter = parameters.getParameter(i);
		var paramName = parameter.getName();
		if (paramName.substring(0, 2) == "__" || 
			protectedParameterArray.indexOf(paramName) < 0) {
			parameters.removeParameter(paramName);
		}
	}
}

function __parameter2QueryCondition(datasetParameter, datasetCondition) {
	if (datasetCondition) {
		datasetCondition.disableControls();
		if (datasetCondition.getCurrent() != null) {
			datasetCondition.cancelRecord();
			if (datasetCondition.getCurrent() != null) datasetCondition.deleteRecord();
		}
		
		datasetCondition.insertRecord();
		var record = datasetParameter.getFirstRecord();
		while (record) {
			var paramType = record.getValue("paramType");
			var value = record.getValue("paramValue");
			switch (name2DataType(paramType)) {
			  case 10:
			  case 11:
			  case 12:
				if (value) {
					value = new Date(parseInt(value));
				}
				break;
			}
			datasetCondition.setValue(record.getValue("paramName"), value);
			record = record.getNextRecord();
		}
		datasetCondition.enableControls();
		datasetCondition.refreshControls();
	}
}

function __queryCondition2Parameter(datasetCondition, datasetParameter) {
	if (datasetCondition && datasetCondition.getCurrent() != null) {
		if (!datasetCondition.postRecord()) return false;
		
		datasetParameter.disableControls();
		while (datasetParameter.getCurrent() != null) {
			datasetParameter.deleteRecord();
		}
		for (var i = 0; i < datasetCondition.getFieldCount(); i++) {
			var field = datasetCondition.getField(i);
			var name = field.getName();
			var dataType = field.getDataType();
			var value = datasetCondition.getValue(i);
			if (value !== null && value !== "") {
				datasetParameter.insertRecord();
				datasetParameter.setValue("paramName", name);
				switch (dataType) {
				  case 10:
				  case 11:
				  case 12:
					value = value.getTime();
					break;
				}
				datasetParameter.setValue("paramValue", value);
				datasetParameter.setValue("paramType", dataType2Name(dataType));
				datasetParameter.postRecord();
			}
		}
		datasetParameter.enableControls();
	}
	return true;
}

// ===================================================

var $datasetDataTableProfile;
var $datasetDataTableColumnProfile;
var __commandSaveTableProfile;
var __commandDeleteTableProfile;
var __profileKeys = null;

function __getProfileKeys() {
	if (__profileKeys == null) {
		__profileKeys = {};
		var props = getViewModel().properties();
		var profileKeys = props.getValue("__profileKeys");
		props.removeParameter("__profileKeys");
		if (profileKeys) {
			var v = profileKeys.split(";");
			for (var i = 0; i < v.length; i += 2) {
				__profileKeys[v[i]] = v[i + 1];
			}
		}
	}
	return __profileKeys;
}

function __dataTablePropertiesToDataset(table, profileKey, dataset) {
	dataset.setValue("id", null);
	dataset.setValue("tableName", profileKey);
	dataset.setValue("fixedColumn", table.getFixedColumn());
	dataset.setValue("showFilterBar", table.isShowFilterBar());
	dataset.setValue("columnDraggable", table.isColumnDraggable());
	dataset.setValue("readOnly", table.isReadOnly());
	dataset.setValue("showFooter", table.isShowFooter());
	dataset.setValue("rowHeight", table.getRowHeight());
}

function __dataTableColumnPropertiesToDataset(column, dataset) {
	dataset.setValue("id", null);
	dataset.setValue("name", column.getName());
	dataset.setValue("label", column.getLabel());
	dataset.setValue("visible", column.isVisible());
	if (column.getType() == "data") {
		dataset.setValue("type", "DataColumn");
		dataset.setValue("field", column.getField());
		dataset.setValue("width", column.getWidth());
		dataset.setValue("readOnly", column.isReadOnly());
		dataset.setValue("rendererType", column.getRendererType());
		dataset.setValue("editorType", column.getEditorType());
		dataset.setValue("resizable", column.isResizable());
		dataset.setValue("filterable", column.isFilterable());
		dataset.setValue("groupable", column.isGroupable());
		var dropDown = column.getDropDown();
		if (dropDown != null && dropDown.id.charAt(0) != "$" && dropDown.id.charAt(0) != "_") {
			dataset.setValue("dropDownType", "ref");
			dataset.setValue("dropDownMeta", dropDown.id);
		}
	} else {
		dataset.setValue("type", "ColumnGroup");
	}
}

function __dataTableToDataset(table, profileKey, datasetTable, datasetColumn) {
	datasetTable.clearData();
	datasetColumn.clearData();
	var dataset = datasetTable;
	dataset.insertRecord();
	__dataTablePropertiesToDataset(table, profileKey, dataset);
	dataset.postRecord();
	dataset = datasetColumn;
	var columnCount = table.getColumnCount();
	for (var i = 0; i < columnCount; i++) {
		var column = table.getColumn(i);
		dataset.insertRecord();
		dataset.setValue("level", 0);
		__dataTableColumnPropertiesToDataset(column, dataset);
		dataset.postRecord();
		if (column.getType() == "group") {
			var subColumnCount = column.getColumnCount();
			for (var j = 0; j < subColumnCount; j++) {
				var subColumn = column.getColumn(j);
				dataset.insertRecord();
				dataset.setValue("level", 1);
				__dataTableColumnPropertiesToDataset(subColumn, dataset);
				dataset.postRecord();
			}
		}
	}
}

function __saveDataTableProfile(table) {
	var profileKey = __getProfileKeys()[table.id];
	if (!profileKey) {
		return;
	}
	
	var dataset = $datasetDataTableProfile;
	if (dataset == null) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetDataTableProfile", "custom");
		$datasetDataTableProfile = dataset;
		dataset.addField("id", 1);
		dataset.addField("tableName", 1);
		dataset.addField("fixedColumn", 4);
		dataset.addField("showFilterBar", 9);
		dataset.addField("columnDraggable", 9);
		dataset.addField("readOnly", 9);
		dataset.addField("showFooter", 9);
		dataset.addField("rowHeight", 4);
		dataset.activate();
	}
	
	dataset = $datasetDataTableColumnProfile;
	if (dataset == null) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetDataTableColumnProfile", "custom");
		$datasetDataTableColumnProfile = dataset;
		dataset.addField("id", 1);
		dataset.addField("name", 1);
		dataset.addField("type", 1);
		dataset.addField("level", 4);
		dataset.addField("label", 1);
		dataset.addField("field", 1);
		dataset.addField("width", 4);
		dataset.addField("visible", 9);
		dataset.addField("readOnly", 9);
		dataset.addField("rendererType", 1);
		dataset.addField("editorType", 1);
		dataset.addField("resizable", 9);
		dataset.addField("filterable", 9);
		dataset.addField("groupable", 9);
		dataset.addField("dropDownType", 1);
		dataset.addField("dropDownMeta", 1);
		dataset.addField("dropDownScript", 1);
		dataset.activate();
	}
	
	__dataTableToDataset(table, profileKey, $datasetDataTableProfile, $datasetDataTableColumnProfile);
	var command = __commandSaveTableProfile;
	if (command == null) {
		command = DoradoFactory.create("MarmotUpdateCommand");
		__commandSaveTableProfile = command;
		command.setAsync(true);
		command.setShowLoadingTip(true);
		command.setAction(__MARMOT_DEFAULT_UPDATE_ACTION);
		command.setResolver("marmot.dataTableProfileBackBean");
		command.setMethod("saveDataTableProfile2");
		command.addDatasetInfo($datasetDataTableProfile);
		command.addDatasetInfo($datasetDataTableColumnProfile);
		command.activate();
	}
	
	var parameters = command.parameters();
	parameters.setValue("profileKey", profileKey);
	command.execute();
}

function __deleteDataTableProfile(table) {
	var profileKey = __getProfileKeys()[table.id];
	if (!profileKey) {
		return;
	}
	
	var command = __commandSaveTableProfile;
	if (command == null) {
		command = DoradoFactory.create("MarmotRPCCommand");
		__commandSaveTableProfile = command;
		command.setAsync(true);
		command.setShowLoadingTip(true);
		command.setAction(__MARMOT_DEFAULT_RPC_ACTION);
		command.setResolver("marmot.dataTableProfileBackBean");
		command.setMethod("deleteDataTableProfile");
		command.activate();
	}
	var parameters = command.parameters();
	parameters.setValue("profileKey", profileKey);
	command.execute();
}

var __menuTableProfile;
var __commandDataTableProfileEdit;

function __getDataTableProfileEditCommand() {
	var command = __commandDataTableProfileEdit;
	if (command == null) {
		command = DoradoFactory.create("RequestCommand");		
		command.setPath("/dataTableProfile.d");
		command.setMethod("post");
		command.activate();
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setWidth(640);
		frame.setHeight(400);
		__commandDataTableProfileEdit = command;
	}
	return command;
}

function __DataTable_showAdvancePropertiesWindow() {
	var command = __getDataTableProfileEditCommand();
	var parameters = command.parameters();
	parameters.setValue("dataTableId", this.id);
	parameters.setValue("profileKey", __getProfileKeys()[this.id]);
	command.execute();
}

function __DataTable_onActive(table) {
	table.showPropertiesWindow = __DataTable_showAdvancePropertiesWindow;
}

function __DataTable_onHeaderClick(table, cell, column) {
	if (column == null) {
		var menu = __menuTableProfile;
		if (menu == null) {
			menu = DoradoFactory.create("Menu");
			var topItem = menu.getTopItem();
			var item = new MenuItem("save", "\u4fdd\u5b58\u5f53\u524d\u663e\u793a\u72b6\u6001");
			item.setIcon(__CONTEXT_PATH + "/marmot/profile/images/save.gif");
			topItem.addItem(item);
			
			item = new MenuItem("delete", "\u5220\u9664\u5f53\u524d\u663e\u793a\u72b6\u6001");
			item.setIcon(__CONTEXT_PATH + "/marmot/profile/images/delete.gif");
			topItem.addItem(item);
			
			item = new MenuItem("showPropertiesWindow", "\u663e\u793a\u5c5e\u6027\u8bbe\u7f6e\u7a97\u53e3");
			item.setIcon(__CONTEXT_PATH + "/marmot/profile/images/maintain.gif");
			topItem.addItem(item);
			
			item = new MenuItem("export2Excel", "\u5bfc\u51fa\u5230Excel");
			item.setIcon(__CONTEXT_PATH + "/marmot/profile/images/excel.gif");
			topItem.addItem(item);
			
			EventManager.addDoradoEvent(menu, "onItemClick", function (menu, item) {
				switch (item.getName()) {
				  case "save":
					__saveDataTableProfile(table);
					break;
				  case "delete":
					__deleteDataTableProfile(table);
					break;
				  case "showPropertiesWindow":
					table.showPropertiesWindow();
					break;
				  case "export2Excel":
					var command = getControl("__commandExport2Excel");
					if (command == null) {
						command = DoradoFactory.create("Export2ExcelCommand", null, "__commandExport2Excel");
						command.activate();
					}
					command.setMethod("post");
					command.setTemplateTable(table);
					command.setDataset(table.getDataset());
					command.setMaxRow(65535);
					command.execute();
					break;
				}
			});
			menu.activate();
		}
		
		var menuBox = menu.show();
		if (menuBox) {
			var pos = getAbsolutePosition(cell);
			menuBox.style.left = pos[0];
			menuBox.style.top = pos[1] + cell.offsetHeight;
		}
		return false;
	} else {
		return true;
	}
}

var __commandAutoFormProfile;

function __getAutoFormProfileCommand() {
	var command = __commandAutoFormProfile;
	if (command == null) {
		command = DoradoFactory.create("RequestCommand");
		command.activate();
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setWidth(640);
		frame.setHeight(400);
		__commandAutoFormProfile = command;
	}
	return command;
}

function __processAutoFormProfileMenuClick(menu, item) {
	switch (item.getName()) {
	  case "showEditor":
		var target = menu.getPopupElement();
		if (target != null) {
			var command = __getAutoFormProfileCommand();
			command.setPath("/autoFormProfile.d");
			command.setMethod("post");
			var parameters = command.parameters();
			parameters.clear();
			parameters.setValue("viewInstanceId", getViewModel().getInstanceId());
			parameters.setValue("autoFormId", target.id);
			parameters.setValue("profileKey", __getProfileKeys()[target.id]);
			command.execute();
		} else {
			alert("Can not find the target AutoForm.");
		}
		break;
	}
}

var __$MOCK = "$MOCK";
var __$LAZY = "$LAZY";
var __$FAVORITE = "$FAVORITE";

function __lazyMenu_onActive(menu) {

	function initLazyParentItems(parentItem) {
		var items = parentItem.getItems();
		var size = items.size();
		for (var i = 0; i < size; i++) {
			var item = items.get(i);
			if (item.getTag() == __$LAZY) {
				item.marmotItemId = item.getName();
				item.$lazyItemSuperGetItems = item.getItems;
				item.getItems = __lazyMenu_getItems;
			} else if (item.getTag() == __$FAVORITE) {
				item.marmotItemId = __$FAVORITE;
				item.$lazyItemSuperGetItems = item.getItems;
				item.getItems = __lazyMenu_getItems;
			} else {
				initLazyParentItems(item);
			}
		}
	}
	
	initLazyParentItems(menu.getTopItem());
	EventManager.addDoradoEvent(menu, "onItemClick", __lazyMenu_onItemClick);
}

function __lazyMenu_onItemClick(menu, item, sourceElement) {
	switch (item.getName()) {
		case "addFavorite": {
			if (!$currentMenuElement) {
				alert("\u8BF7\u9996\u5148\u6FC0\u6D3B\u60A8\u8981\u6536\u85CF\u7684\u83DC\u5355\!");
				return;
			}
		
			var command = __Favorite_getAddFavoriteCommand();			
			var params = command.parameters();			
			params.setValue("label", $currentMenuElement.getLabel());
			params.setValue("icon", $currentMenuElement.getIcon());
			params.setValue("path", $currentMenuElement.getPath());
			command.execute(function(success) {
					if (success) {											
						var favoriteItem = marmotLoaded;
						favoriteItem.marmotLoaded = false;
					}
				});
			break;
		}
		
		case "maintainFavorite": {
			var command = __Favorite_getMaintainFavoriteCommand();
			if (command.execute()) {
				var favoriteItem = item.getParent();
				favoriteItem.marmotLoaded = false;
			}
			break;
		}
	}
	return false;
}

function __lazyMenu_getItems() {

	function addMockSubItem(item) {
		var mockItem = new MenuItem(__$MOCK);
		item.addItem(mockItem);
	}

	if (!this.marmotLoaded) {
		this.marmotLoaded = true;		
		if (this.getItems().size() > 0) {		
			var mockItem = this.getItem(__$MOCK);
			if (mockItem) mockItem.remove();
		
			var parentItemId = this.marmotItemId;
			if (parentItemId == __$FAVORITE) {
				var dataset = __lazyMenu_getDatasetFavorite();
				dataset.flushData();
				__lazyMenu_refreshFavoriteItems(this, dataset);
			}
			else {
				var dataset = __lazyMenu_getDatasetMenuItem();
				if (parentItemId && parentItemId != "$null") {
					dataset.parameters().setValue("parentItemId", parentItemId);
				} else {
					dataset.parameters().clear();
				}
				dataset.flushData();
				
				var isLastItemSeperator = true;
				var record = dataset.getFirstRecord();
				while (record) {
					var id = record.getValue("id");
					var item;
					
					if (record.getValue("type") == 0) {
						item = new MenuItem(id, record.getValue("label"));
						item.marmotItemId = id;
						var icon = record.getValue("icon");
						if (icon) {
							item.setIcon(icon);
						}
						icon = record.getValue("disableIcon");
						if (icon) {
							item.setDisableIcon(icon);
						}
						item.setDisabled(!record.getValue("enabled"));
						item.setVisible(record.getValue("visible"));
						item.setPath(record.getValue("path"));
						
						if (record.getValue("subItemCount") > 0) {
							addMockSubItem(item);
							item.$lazyItemSuperGetItems = item.getItems;
							item.getItems = __lazyMenu_getItems;
						}
						
						this.addItem(item);
						isLastItemSeperator = false;
					}
					else if (!isLastItemSeperator) {
						item = new MenuItemSeperator();
						this.addItem(item);
						isLastItemSeperator = true;
					}
					
					record = record.getNextRecord();
				}
			}
		}
	}
	return this.$lazyItemSuperGetItems();
}

function __lazyMenu_refreshFavoriteItems(favoriteItem, dataset) {
	var items = favoriteItem.getItems();
	for (var i = items.size() - 1; i >= 0; i--) {
		var item = items.get(i);
		if (item.getTag() == __$FAVORITE) item.remove();
	}

	var record = dataset.getFirstRecord();
	while (record) {
		var id = record.getValue("id");
		var item = new MenuItem(id, record.getValue("label"));
		var icon = record.getValue("icon");
		if (!icon) icon = "marmot/menu/images/favorite.gif";
		item.setIcon(icon);
		item.setPath(record.getValue("path"));
		item.setTag(__$FAVORITE);
		favoriteItem.addItem(item);
		record = record.getNextRecord();
	}
}

function __lazyMenu_getDatasetMenuItem() {
	var dataset = getDataset("$datasetMenuItem");
	if (!dataset) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetMenuItem", "custom");
		dataset.addField("id", 1);
		dataset.addField("type", 4);
		dataset.addField("label", 1);
		dataset.addField("icon", 1);
		dataset.addField("disableIcon", 1);
		dataset.addField("visible", 9);
		dataset.addField("enabled", 9);
		dataset.addField("path", 1);
		dataset.addField("subItemCount", 4);
		dataset.addField("description", 1);
		dataset.addField("meta1", 1);
		dataset.addField("meta2", 1);
		dataset.addField("meta3", 1);
		dataset.activate();
	}
	return dataset;
}

function __lazyMenu_getDatasetFavorite() {
	var dataset = getDataset("$datasetFavorite");
	if (!dataset) {
		dataset = DoradoFactory.create("Dataset", null, "$datasetFavorite", "custom");
		dataset.addField("id", 1);
		dataset.addField("label", 1);
		dataset.addField("icon", 1);
		dataset.addField("disableIcon", 1);
		dataset.addField("path", 1);
		dataset.activate();
	}
	return dataset;
}

function __lazyNavTree_onActive(tree) {
	EventManager.addDoradoEvent(tree, "onClick", __lazyNavTree_onClick);
}

function __lazyNavTree_beforeExpandNode(tree, node) {
	if (node.hasExpanded()) {
		return;
	}
	
	if (!node.marmotItemId) {
		var tag = node.getTag();
		if (tag && tag.charAt(0) == "$") {
			node.marmotItemId = tag.substring(1);
		}
	}
	
	var parentItemId = node.marmotItemId;
	if (parentItemId) {
		if (parentItemId == "FAVORITE") {
			__lazyNavTree_refreshFavoriteNodes(node);
		}
		else {
			var dataset = __lazyMenu_getDatasetMenuItem();
			if (parentItemId && parentItemId != "$null") {
				dataset.parameters().setValue("parentItemId", parentItemId);
			} else {
				dataset.parameters().clear();
			}
			
			dataset.flushDataAsync(function (succeed) {
				if (succeed) {
					var record = dataset.getFirstRecord();
					while (record) {
						if (record.getValue("enabled") && record.getValue("visible") && record.getValue("type") == 0) {
							var id = record.getValue("id");
							var childNode = new DefaultTreeNode(record.getValue("label"));
							childNode.marmotItemId = id;
							var icon = record.getValue("icon");
							if (icon) {
								childNode.setIcon(icon);
							}
							childNode.setPath(record.getValue("path"));
							childNode.setHasChild(record.getValue("subItemCount") > 0);
							node.addNode(childNode);
						}
						record = record.getNextRecord();
					}
				}
			});
		}
	}
}

function __lazyNavTree_onClick(tree) {
	var currentNode = tree.getCurrentNode();
	if (!currentNode) return;
	
	switch (currentNode.getTag()) {
		case "addFavorite": {
			if (!$currentMenuElement) {
				alert("\u8BF7\u9996\u5148\u6FC0\u6D3B\u60A8\u8981\u6536\u85CF\u7684\u83DC\u5355\!");
				return;
			}
		
			var command = __Favorite_getAddFavoriteCommand();			
			var params = command.parameters();			
			params.setValue("label", $currentMenuElement.getLabel());
			params.setValue("icon", $currentMenuElement.getIcon());
			params.setValue("path", $currentMenuElement.getPath());
			command.execute(function(success) {
					if (success) {											
						var favoriteNode = currentNode.getParent();
						__lazyNavTree_refreshFavoriteNodes(favoriteNode);
					}
				});
			break;
		}
		
		case "maintainFavorite": {
			var command = __Favorite_getMaintainFavoriteCommand();
			var eventHandler = function(command) {
				var favoriteNode = currentNode.getParent();
				__lazyNavTree_refreshFavoriteNodes(favoriteNode);
			}

			var eventHandlers = EventManager.getDoradoEvents(command, "onSuccess");
			if (!eventHandlers || eventHandlers.indexOf(eventHandler) < 0) {
				EventManager.addDoradoEvent(command, "onSuccess", eventHandler);
			}
			command.execute();
			break;
		}
	}
	return false;
}

function __lazyNavTree_refreshFavoriteNodes(favoriteNode) {
	var dataset = __lazyMenu_getDatasetFavorite();
	dataset.flushDataAsync(function (succeed) {
			if (succeed) {
				var node = favoriteNode.getFirstChild();
				while (node) {
					var tempNode = node;
					node = node.getNextSibling();		
					if (tempNode.getTag() == __$FAVORITE) {
						tempNode.remove();
					}
				}
			
				var record = dataset.getFirstRecord();
				while (record) {
					var node = new DefaultTreeNode(record.getValue("label"));
					var icon = record.getValue("icon");
					if (!icon) icon = "marmot/menu/images/favorite.gif";
					node.setIcon(icon);
					node.setPath(record.getValue("path"));
					node.setHasChild(false);
					node.setTag(__$FAVORITE);
					favoriteNode.addNode(node);
					record = record.getNextRecord();
				}
			}
		});
}

function __Favorite_getAddFavoriteCommand() {	
	var command = getControl("$commandAddFavorite");
	if (command == null) {
		command = DoradoFactory.create("MarmotRPCCommand", null, "$commandAddFavorite");
		command.setAsync(true);
		command.setShowLoadingTip(true);
		command.setAction(__MARMOT_DEFAULT_RPC_ACTION);
		command.setResolver("marmot.favoriteBackBean");
		command.setMethod("addFavorite");
		command.activate();
	}
	return command;
}

function __Favorite_getDeleteFavoriteCommand() {	
	var command = getControl("$commandDeleteFavorite");
	if (command == null) {
		command = DoradoFactory.create("MarmotRPCCommand", null, "$commandDeleteFavorite");
		command.setAsync(true);
		command.setShowLoadingTip(true);
		command.setAction(__MARMOT_DEFAULT_RPC_ACTION);
		command.setResolver("marmot.favoriteBackBean");
		command.setMethod("deleteFavorite");
		command.activate();
	}
	return command;
}

function __Favorite_getMaintainFavoriteCommand() {
	var command = getControl("$commandMaintainFavorite");
	if (!command) {
		command = DoradoFactory.create("RequestCommand", null, "$commandMaintainFavorite");
		command.setPath("/menu.favoriteMaintain.d");
		command.setMethod("post");
		command.parameters().setValue("hideAddButton", true);
		var frame = command.getFrame();
		frame.setTarget("_exclusive_subwindow");
		frame.setCenter(true);
		frame.setWidth(300);
		frame.setHeight(350);
		command.activate();
	}
	return command;
}

// ===================================================

var $currentMenuElement = null;

function openPath(path, title) {
	if (path.substring(0, 11) == "javascript:") {
		eval(path.substring(11));
	}
	else {
		showLoadingAnimation();
		
		var subwindow = document.getElementById("subwindowWorkspace");;
		if (subwindow) {
			if (!title) title = "";
			subwindow.setTitle(title);
		}
		
		setTimeout("document.getElementById(\"frameWorkspace\").contentWindow.location.href = unescape(\"" +
			path + "\")", 0);
	}
}

function showLoadingAnimation() {
  var loadingAnimation = document.getElementById("loadingAnimation");
  if (loadingAnimation) loadingAnimation.style.display = "";
}
  
function hideLoadingAnimation() {
  var loadingAnimation = document.getElementById("loadingAnimation");
  if (loadingAnimation) loadingAnimation.style.display = "none";
}

function $frameWorkspaceLoaded() {
  hideLoadingAnimation();
  
  var title;
  try {
    var frameWorkspace = document.getElementById("frameWorkspace");
    title = frameWorkspace.contentWindow.document.title;
  }
  catch(e) {
  }
  
  if (title) {
    var subwindow = document.getElementById("subwindowWorkspace");;
    if (subwindow) {
    	if (subwindow.setTitle) {
    		subwindow.setTitle(title);
    	}
    	else {
    		setTimeout(function() {
    				if (subwindow.setTitle) subwindow.setTitle(title);
    			}, 200);
    	}
    }
  }
}

function changeCaptchaImage() {
  var editor = document.getElementById("editorCaptchaCode");
  if (editor) editor.value = "";
  
  var img = document.getElementById("captchaImage");
  if (img) {
    img.src = "sample/main/style1/images/captcha-loading.gif";
    setTimeout(function() {
        img.src = "authentication.getCaptchaImage.d?" + (new Date().getTime());
      }, 200);
  }
}
